package com.example.demo.component;

import com.example.demo.util.Assert;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zyc
 */
@Component
public class SpringHolder implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public static HttpServletRequest getRequest() {
        return getServletRequestAttributes().getRequest();
    }

    public static HttpServletResponse getResponse() {
        return getServletRequestAttributes().getResponse();
    }

    public static HttpSession getSession() {
        return getSession(true);
    }

    public static HttpSession getSession(boolean allowCreate) {
        return getRequest().getSession(allowCreate);
    }

    public static Cookie[] getCookie() {
        return getRequest().getCookies();
    }

    public static Cookie getCookie(String name) {
        Cookie[] cookies = getRequest().getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
        return null;
    }

    public static String getCookieValue(String name) {
        Cookie cookie;
        return (cookie = getCookie(name)) == null ? "" : cookie.getValue();
    }

    public static void setCookie(String name, String value) {
        Assert.isNull(name, "cookie名称不能为空");
        Assert.isNull(name, "cookie的值不能为空");
        Cookie cookie = new Cookie(name, value);
        getResponse().addCookie(cookie);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
